package com.ruoyi.web.controller.subjecttree;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.Ztree;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.YcSubject;
import com.ruoyi.system.service.IYcSubjectService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * 学科Controller
 *
 * @author 杨琛
 * @date 2020-11-21
 */
@Controller
@RequestMapping("/system/subject")
public class YcSubjectController extends BaseController {
    private String prefix = "system/subject";

    /**
     * 用来添加时校验集合
     */
    private List<String> subjectNameList = new ArrayList<>();
    /**
     * 用来删除时校验集合
     */
    private List<String> subjectNameDeleteList = new ArrayList<>();

    /**
     * 用来编辑时校验集合以及接受的参数
     */
    private List<String> subjectNameEditList = new ArrayList<>();
    private Long parentId;

    /**
     * 用来接受编辑时获取初始化的学科名称
     */
    private String subjectName;


    /**
     * 用来接受新增科目的状态
     */
    private String status;

    /**
     * "1"代表菜单为禁用
     */
    private static final String STOP ="1";

    @Autowired
    private IYcSubjectService ycSubjectService;

    @RequiresPermissions("system:subject:view")
    @GetMapping()
    public String subject() {
        return prefix + "/subject";
    }

    /**
     * 查询学科树列表
     */
    @RequiresPermissions("system:subject:list")
    @PostMapping("/list")
    @ResponseBody
    public List<YcSubject> list(YcSubject ycSubject) {
        List<YcSubject> list = ycSubjectService.selectYcSubjectList(ycSubject);
        return list;
    }

    /**
     * 导出学科列表
     */
    @RequiresPermissions("system:subject:export")
    @Log(title = "学科", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(YcSubject ycSubject) {
        List<YcSubject> list = ycSubjectService.selectYcSubjectList(ycSubject);
        ExcelUtil<YcSubject> util = new ExcelUtil<YcSubject>(YcSubject.class);
        return util.exportExcel(list, "subject");
    }

    /**
     * 新增学科
     */
    @GetMapping(value = {"/add/{subjectId}", "/add/"})
    public String add(@PathVariable(value = "subjectId", required = false) Long subjectId, ModelMap mmap) {
        //按照被增加学科的id查询出,被增加学科的所有信息
        List<YcSubject> ycSubjects = ycSubjectService.selectYcSubjectSubordinate(subjectId);
        //获取点击的学科是否停用 "0"正常 "1"停用
        this.status=ycSubjectService.selectYcSubjectById(subjectId).getStatus();
        //将查询出来的集合遍历到新集合当中 this.subjectName subjectName
        ycSubjects.stream().forEach(item -> this.subjectNameList.add(item.getSubjectName().replace(" ", "")));
        if (StringUtils.isNotNull(subjectId)) {
            mmap.put("ycSubject", ycSubjectService.selectYcSubjectById(subjectId));
        }
        return prefix + "/add";
    }

    /**
     * 新增保存学科
     */
    @RequiresPermissions("system:subject:add")
    @Log(title = "学科", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(YcSubject ycSubject) {
        //如果该学科的子学科名字相同则禁止添加
        if (STOP.equals(this.status)){
            return AjaxResult.error("已停用,禁止添加");
        }
        if (this.subjectNameList.contains(ycSubject.getSubjectName().replace(" ", ""))) {
            //清空集合
            subjectNameList.clear();
            return AjaxResult.error("该学科下已有相同的学科名称");
        }
        ycSubject.setCreateBy(ShiroUtils.getLoginName());
        return toAjax(ycSubjectService.insertYcSubject(ycSubject));
    }

    /**
     * 修改学科
     */
    @GetMapping("/edit/{subjectId}")
    public String edit(@PathVariable("subjectId") Long subjectId, ModelMap mmap) {
        //按照被编辑学科的id查询出上级菜单的id
        Long parentId = ycSubjectService.selectYcSubjectById(subjectId).getParentId();
        this.parentId = parentId;
        YcSubject ycSubject = ycSubjectService.selectYcSubjectById(subjectId);
        this.subjectName = ycSubject.getSubjectName().replace(" ", "");
        mmap.put("ycSubject", ycSubject);
        return prefix + "/edit";
    }

    /**
     * 修改保存学科
     */
    @RequiresPermissions("system:subject:edit")
    @Log(title = "学科", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(YcSubject ycSubject) {
        //ycSubject.getParentId():获取更改后编辑页面的父学科id
        //this.parentId:获取默认的父学科id
        //判断用户是否修改了父学科  如果修改了父学科 则和前端传过来的父学科id不相等
        if (!ycSubject.getParentId().equals(this.parentId)) {
            //因为不想等  所以查询条件要更改为用户修改过后的id
            List<YcSubject> ycSubjects = ycSubjectService.selectYcSubjectSubordinate(ycSubject.getParentId());
            //将集合遍历到新的集合里
            ycSubjects.stream().forEach(item -> this.subjectNameEditList.add(item.getSubjectName().replace(" ", "")));
            if (this.subjectNameEditList.contains(ycSubject.getSubjectName().replace(" ", ""))) {
                //清空集合
                subjectNameEditList.clear();
                return AjaxResult.error("该学科下已有相同的学科名称");
            }
            return toAjax(ycSubjectService.updateYcSubject(ycSubject));
            //如果相等,就代表用户没有修改父学科
        } else if (ycSubject.getParentId().equals(this.parentId)) {
            //如果用户编辑的时候修改了学科名称,所以会不相等,则走正常的流程不按条件删除默认值
            if (!this.subjectName.trim().equals(ycSubject.getSubjectName().replace(" ", ""))) {
                    List<YcSubject> ycSubjects = ycSubjectService.selectYcSubjectSubordinate(this.parentId);
                    ycSubjects.stream().forEach(item -> this.subjectNameEditList.add(item.getSubjectName().replace(" ", "")));
                    if (this.subjectNameEditList.contains(ycSubject.getSubjectName().replace(" ", ""))) {
                        //清空集合
                        subjectNameEditList.clear();
                        return AjaxResult.error("该学科下已有相同的学科名称");
                }
                this.subjectNameEditList.clear();
                return toAjax(ycSubjectService.updateYcSubject(ycSubject));
            }
            //如果用户编辑的时候没有修改学科名称,所以会相等,则在查询出学科里删掉默认的学科名称防止编辑失败
            List<YcSubject> ycSubjects = ycSubjectService.selectYcSubjectSubordinate(this.parentId);
            ycSubjects.stream().forEach(item -> this.subjectNameEditList.add(item.getSubjectName().replace(" ", "")));
            this.subjectNameEditList.remove(ycSubject.getSubjectName().replace(" ", ""));
            if (this.subjectNameEditList.contains(ycSubject.getSubjectName().replace(" ", ""))) {
                //清空集合
                subjectNameEditList.clear();
                return AjaxResult.error("该学科下已有相同的学科名称");
            }
            this.subjectNameEditList.clear();
            return toAjax(ycSubjectService.updateYcSubject(ycSubject));
        }

        return toAjax(ycSubjectService.updateYcSubject(ycSubject));
    }

    /**
     * 删除
     */
    @RequiresPermissions("system:subject:remove")
    @Log(title = "学科", businessType = BusinessType.DELETE)
    @GetMapping("/remove/{subjectId}")
    @ResponseBody
    public AjaxResult remove(@PathVariable("subjectId") Long subjectId) {
        //按照被增加学科的id查询出,被增加学科的所有信息
        List<YcSubject> ycSubjects = ycSubjectService.selectYcSubjectSubordinate(subjectId);
        //将查询出来的集合遍历到新集合当中 this.subjectNameDelete 指的是该类名字为subjectNameDelete下的全局集合
        ycSubjects.stream().forEach(item -> this.subjectNameDeleteList.add(item.getSubjectName().replace(" ", "")));
        //如果该学科下有子学科则禁止删除
        if (!this.subjectNameDeleteList.isEmpty()) {
            //清空集合
            subjectNameDeleteList.clear();
            return AjaxResult.error("该目录下有子学科");
        }
        return toAjax(ycSubjectService.deleteYcSubjectById(subjectId));
    }

    /**
     * 选择学科树
     */
    @GetMapping(value = {"/selectSubjectTree/{subjectId}", "/selectSubjectTree/"})
    public String selectSubjectTree(@PathVariable(value = "subjectId", required = false) Long subjectId, ModelMap mmap) {
        if (StringUtils.isNotNull(subjectId)) {
            mmap.put("ycSubject", ycSubjectService.selectYcSubjectById(subjectId));
        }
        return prefix + "/tree";
    }

    /**
     * 加载学科树列表
     */
    @GetMapping("/treeData")
    @ResponseBody
    public List<Ztree> treeData() {
        List<Ztree> ztrees = ycSubjectService.selectYcSubjectTree();
        return ztrees;
    }

}
